package com.letv.android.client.webview;

import java.util.HashMap;

import org.json.JSONObject;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.webkit.WebView;

import com.letv.core.utils.LogInfo;

/**
 * Created by liuxx on 14/12/11.
 * 注册广播获取当前电池电量
 */
//当JS调用时注册广播，注册时广播会接受到电量值
public class BatteryBroadcastReceiver extends BroadcastReceiver {
    private JSInBean mJSInBean;
    private WebView mWebView;
    private Context mContext;

    public BatteryBroadcastReceiver(JSInBean jsInBean, WebView webView, Context context) {
        this.mContext = context;
        this.mJSInBean = jsInBean;
        this.mWebView = webView;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if (Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())) {
            int level = intent.getIntExtra("level", 0);
            int scale = intent.getIntExtra("scale", 0);//电量最大值
            LogInfo.log("lxx", "level: " + level + ", scale: " + scale);
            HashMap<String, Integer> powerMap = new HashMap<String, Integer>();
            powerMap.put("level", level);
            final String callString = JavaScriptinterface.buildupJSCallString(mJSInBean.getCallback(), mJSInBean.getCallback_id(), (new JSONObject(powerMap)).toString());
            LogInfo.log("lxx", "core_getPowerLevel callString: " + callString);
            mWebView.post(new Runnable() {
                @Override
                public void run() {
                    mWebView.loadUrl(callString);
                }
            });
            mContext.unregisterReceiver(this);//close reciver,or send level to JS all the time.
        }
    }
}
